<template>
  <div class="container">
    <h3>vue+openlayers: 加载百度地图</h3>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import { Tile } from 'ol/layer'
import { XYZ, TileImage } from 'ol/source'
import TileGrid from 'ol/tilegrid/TileGrid'
export default {
  data() {
    return {
      map: null
    }
  },
  mounted() {
    this.initmap()
  },
  methods: {
    initmap() {
      let resolutions = [] //分辨率
      let baiduX, baiduY //百度坐标
      for (let i = 0; i < 19; i++) { //20层
        resolutions[i] = Math.pow(2, 18 - i) //分辨率
      } //百度坐标系
      let tilegrid = new TileGrid({
        origin: [0, 0], //设置原点坐标
        resolutions: resolutions //设置分辨率
      }) //百度地图
      let baidu_source = new TileImage({
        projection: 'EPSG:3857', //投影坐标系
        tileGrid: tilegrid, //设置网格
        tileUrlFunction: function(tileCoord) { //切片网址
          if (!tileCoord) return '' //判断是否为空
          let z = tileCoord[0] //切片层级
          let x = tileCoord[1] //切片x坐标
          let y = tileCoord[2] //切片y坐标
          // 百度瓦片服务url将负数使用M前缀来标识 ,对编号xy值进行处理
          baiduX = (x<0) ? x : 'M' + (-x); //x坐标
          baiduY = -y; //y坐标
          return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + baiduX + "&y=" + baiduY + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1"
        }
      })
      let baidu_layer = new Tile({ //百度地图图层
        source: baidu_source //设置数据源
      })
      this.map = new Map({
        target: 'vue-openlayers', //地图容器div的ID
        layers: [baidu_layer], // 图层
        view: new View({
          projection: 'EPSG:3857', //投影坐标系
          center: [13531290.967373039, 4675318.865056401], //中心点
          zoom: 12 //缩放级别
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>